package com.macro.mall.controller.callbak;

import com.fasterxml.jackson.databind.ObjectMapper;


import com.macro.mall.model.XhsEncryptedMessage;
import com.macro.mall.model.XhsEvent;
import com.macro.mall.utils.MsgDecrypt;
import com.macro.mall.utils.MsgSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

/**
 * 小红书回调控制器
 */
@RestController
@RequestMapping("/huadi/xhs/callbackaa")
public class XhsCallbackController {

    private static final Logger log = LoggerFactory.getLogger(XhsCallbackController.class);

    // 配置参数(实际项目中应从配置文件中读取)
    private final String token = "zhijia";
    private final String encodingAesKey = "LoNnW7rMPCP7rArFh7r446x576p63XSrC3Ak7xSJKB7";

    /**
     * URL验证接口(GET请求)
     */
    @GetMapping
    public String verifyUrl(
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam("echostr") String echostr) throws Exception {

        log.info("收到小红书URL验证请求: signature={}, timestamp={}, nonce={}, echostr={}",
                signature, timestamp, nonce, echostr);

        // 计算签名
        String calculatedSignature = MsgSignature.getSignature(token, timestamp, nonce, "");

        // 验证签名
        if (calculatedSignature.equals(signature)) {
            log.info("URL验证成功");
            return echostr;
        }

        log.error("URL验证失败: 签名不匹配");
        return "signature verification failed";
    }

    /**
     * 消息接收接口(POST请求)
     */
    @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
    public String handleMessage(@RequestBody XhsEncryptedMessage encryptedMessage) {
        log.info("接收到小红书回调消息通知：{}",encryptedMessage.toString());
        try {
            log.info("收到小红书消息推送: Nonce={}, Timestamp={}",
                    encryptedMessage.getNonce(), encryptedMessage.getTimestamp());

            // 1. 验证签名
            String calculatedSignature = MsgSignature.getSignature(
                    token,
                    encryptedMessage.getTimestamp(),
                    encryptedMessage.getNonce(),
                    encryptedMessage.getEncrypt());

            if (!calculatedSignature.equals(encryptedMessage.getMsgSignature())) {
                log.error("签名验证失败");
                return "signature verification failed";
            }

            // 2. 解密消息
            String decryptedJson = MsgDecrypt.decrypt(
                    encryptedMessage.getEncrypt(),
                    encodingAesKey);

            log.info("解密后的消息内容: {}", decryptedJson);

            // 3. 解析JSON
            ObjectMapper objectMapper = new ObjectMapper();
            XhsEvent event = objectMapper.readValue(decryptedJson, XhsEvent.class);

            // 4. 处理事件(异步执行)
            new Thread(() -> {
                try {
                    handleEvent(event);
                } catch (Exception e) {
                    log.error("处理事件异常", e);
                }
            }).start();

            // 5. 返回success
            return "success";

        } catch (Exception e) {
            log.error("处理小红书消息异常", e);
            return "success"; // 即使出错也要返回success避免重试
        }
    }

    /**
     * 处理具体事件
     */
    private void handleEvent(XhsEvent event) {
        log.info("处理事件: Event={}, OrderType={}, OrderId={}",
                event.getEvent(), event.getOrderType(), event.getOrderId());

        // 根据事件类型处理
        switch (event.getEvent()) {
            case "PAY_RESULT":
                handlePaymentResult(event);
                break;
            // 可以添加其他事件类型的处理
            default:
                log.warn("未知的事件类型: {}", event.getEvent());
        }
    }

    /**
     * 处理支付结果事件
     */
    private void handlePaymentResult(XhsEvent event) {
        log.info("处理支付结果: OrderId={}, Status={}, Amount={}",
                event.getOrderId(), event.getStatus(), event.getTotalAmount());

        // 根据订单类型处理
        if (event.getOrderType() == 1) { // 主单
            if (event.getStatus() == 2) { // 支付成功
                // 更新订单状态为已支付
                log.info("订单支付成功: {}", event.getOutOrderId());

                // 处理券码信息
                if (event.getVoucherInfos() != null) {
                    for (XhsEvent.VoucherInfo voucher : event.getVoucherInfos()) {
                        //
                        log.info("生成券码: {}", voucher.getVoucherCode());
                    }
                }
            } else if (event.getStatus() == 998) { // 支付取消
                log.info("订单支付取消: {}", event.getOutOrderId());
            }
        }
        // 可以添加其他订单类型的处理
    }
}
